

import logging
import requests

from base.base_login import BaseLogin
from base.env_config import ENV

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def hook_response(response, *args, **kwargs):
    logger.info(f"接口响应数据为: {response.text}")

class BaseRequest:
    def __init__(self):
        self.session = requests.Session()
        self.session.hooks['response'].append(hook_response)


class MerRequests(BaseRequest, BaseLogin):
    def __init__(self):
        super().__init__()
        self.session.headers.update({'authori-zation': self.merchant_login(), "content-type": "application/json"})

    def get(self, api_name, url: str, params: dict = None):
        full_url = ENV.MER_HOST + url
        logger.info(f"接口 {api_name} 请求URL: {full_url}, 参数: {params}")
        try:
            response = self.session.get(full_url, params=params, timeout=10)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"接口 {api_name} 调用失败: {str(e)}")
            # 返回模拟的错误响应，以便代码能够继续运行
            return {"code": 500, "msg": f"接口调用失败: {str(e)}", "data": None}

    def post(self, api_name, url: str, data: dict = None):
        full_url = ENV.MER_HOST + url
        logger.info(f"接口 {api_name} 请求URL: {full_url}, 数据: {data}")
        try:
            response = self.session.post(full_url, json=data, timeout=10)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"接口 {api_name} 调用失败: {str(e)}")
            # 返回模拟的错误响应，以便代码能够继续运行
            return {"code": 500, "msg": f"接口调用失败: {str(e)}", "data": None}


